#include "fileTable.h"

int createFileTable(MYSQL* mysql){
    char sql[4096] = "create table userfile (id int auto_increment,filename varchar(50),owner_id int,parent_directory_id int,hash varchar(65),filetype char(1), filepath varchar(255),is_deleted int,primary key(id),unique key(owner_id,filepath))";
    int qret = mysql_query(mysql,sql);
    if(qret != 0){
        fprintf(stderr,"mysql_query : %s\n",mysql_error(mysql));
        return -1;
    }
    bzero(sql,4096);
    strcpy(sql,"create index idx_parent_directory_id on userfile(parent_directory_id)");
    qret = mysql_query(mysql,sql);
    if(qret != 0){
        fprintf(stderr,"mysql_query : %s\n",mysql_error(mysql));
        return -1;
    }
    bzero(sql,4096);
    strcpy(sql,"create index idx_hash_prefix on userfile(`hash`(20))");
    qret = mysql_query(mysql,sql);
    if(qret != 0){
        fprintf(stderr,"mysql_query : %s\n",mysql_error(mysql));
        return -1;
    }
    // bzero(sql,4096);
    // strcpy(sql,"create index idx_owner_id on userfile(owner_id)");
    // qret = mysql_query(mysql,sql);
    // if(qret != 0){
    //     fprintf(stderr,"mysql_query : %s\n",mysql_error(mysql));
    //     return -1;
    // }
    return 0;
}

int delete_from(MYSQL* mysql,fileMetaData_t* meta){
    char sql[1024] = {0};
    sprintf(sql,"update userfile set is_deleted = 1 where id = %d",meta->file_id);
    int qret = mysql_query(mysql,sql);
    if(qret != 0){
        fprintf(stderr,"mysql_query : %s\n",mysql_error(mysql));
        return -1;
    }
    return 0;
} 

int insert_into(MYSQL* mysql,fileMetaData_t* meta){
    char sql[1024] = {0};
    char filetype;
    if(meta->file_type == 1){
        filetype = 'D';
        sprintf(sql,"replace into userfile (filename,owner_id,parent_directory_id,hash,filetype,filepath,is_deleted) values ('%s',%d,%d,NULL,'%c','%s',%d)",meta->filename,meta->owner_id,meta->parent_directory_id,filetype,meta->path,0);
        printf("insert_into执行的sql语句是：%s\n",sql);
    }
    else{
        filetype = '-';
        sprintf(sql,"replace into userfile (filename,owner_id,parent_directory_id,hash,filetype,filepath,is_deleted) values ('%s',%d,%d,'%s','%c','%s',%d)",meta->filename,meta->owner_id,meta->parent_directory_id,meta->hash,filetype,meta->path,0);
        printf("insert_into执行的sql语句是：%s\n",sql);
    }
    //sprintf(sql,"replace into userfile (filename,owner_id,parent_directory_id,hash,filetype,filepath,is_deleted) values ('%s',%d,%d,'%s','%c','%s',%d)",meta->filename,meta->owner_id,meta->parent_directory_id,meta->hash,filetype,meta->path,0);
    int qret = mysql_query(mysql,sql);                                                              
    if(qret != 0){ 
        fprintf(stderr,"mysql_query : %s\n",mysql_error(mysql));
        return -1; 
    }   
    return 0;
}



